using System.Net;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Markdig;
using UniversalAdminSystem.Application.FileStorage.Interfaces;

namespace UniversalAdminSystem.Infrastructure.FileStorage.Parsers;

public sealed partial class MdParseService : IDocParser
{
    private static readonly Regex _blankLines = MyRegex();

    public async Task<string> ParseAsync(string path)
    {
        if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("文件路径不能为空", nameof(path));
        using var reader = new StreamReader(path);
        var mdContent = await reader.ReadToEndAsync();
        return Convert(mdContent);
    }

    private static string Convert(string markdown)
    {
        if (string.IsNullOrWhiteSpace(markdown)) return string.Empty;
        var html = Markdown.ToHtml(markdown, new MarkdownPipelineBuilder().UseAdvancedExtensions().Build());
        var doc = new HtmlDocument();
        doc.LoadHtml(html);
        doc.DocumentNode.SelectNodes("//script|//style|//comment()")?.ToList().ForEach(n => n.Remove());
        var text = WebUtility.HtmlDecode(doc.DocumentNode.InnerText);
        return _blankLines.Replace(text.Trim(), "\n\n");
    }

    [GeneratedRegex(@"\r?\n{2,}", RegexOptions.Compiled)]
    private static partial Regex MyRegex();
}